package com.example.academic_affairs_system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.academic_affairs_system.mapper.AasClassCoursesMapper;
import com.example.academic_affairs_system.model.entity.AasClassCourses;
import com.example.academic_affairs_system.model.entity.AasClassStudent;
import com.example.academic_affairs_system.model.vo.clazz.ClassInfoVO;
import com.example.academic_affairs_system.model.vo.courses.CoursesVO;
import com.example.academic_affairs_system.service.IAasClassCoursesService;
import com.example.academic_affairs_system.service.IAasClassStudentService;
import com.example.academic_affairs_system.service.IAasStudentCoursesService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author hjx
 * @since 2023-01-31
 */
@Service
public class AasClassCoursesServiceImpl extends ServiceImpl<AasClassCoursesMapper, AasClassCourses>
    implements IAasClassCoursesService {
  @Resource IAasClassStudentService iAasClassStudentService;
  @Resource IAasStudentCoursesService iAasStudentCoursesService;

  @Override
  @Transactional
  public int addRelated(long classId, long coursesId) {
    // 绑定班级与课程
    AasClassCourses aasClassCourses = new AasClassCourses();
    aasClassCourses.setClassId(classId).setCoursesId(coursesId);
    int insert = baseMapper.insert(aasClassCourses);
    if (insert > 0) {
      List<AasClassStudent> classStudents =
          iAasClassStudentService.getClassStudentByClassId(classId);
      // 批量关联
      if (CollectionUtil.isNotEmpty(classStudents)) {
        insert +=
            iAasStudentCoursesService.batchRelated(
                classStudents.stream()
                    .map(AasClassStudent::getStudentId)
                    .collect(Collectors.toList()),
                Collections.singletonList(coursesId));
      }
    }
    return insert;
  }

  @Override
  public boolean reRelated(long classId, long coursesId) {
    return baseMapper.selectOne(
            Wrappers.<AasClassCourses>lambdaQuery()
                .eq(AasClassCourses::getClassId, classId)
                .eq(AasClassCourses::getCoursesId, coursesId))
        != null;
  }

  @Override
  public List<CoursesVO> getClassCoursesVOList(long classId) {
    return baseMapper.getClassCoursesVOByClassId(classId);
  }

  @Override
  public List<ClassInfoVO> getClassInfoByCoursesId(long coursesId) {
    return baseMapper.getClassVOByCoursesId(coursesId);
  }
}
